package sd.zhr.moodcapsule.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import sd.zhr.moodcapsule.common.Wrapper;
import sd.zhr.moodcapsule.common.WrapMapper;
import sd.zhr.moodcapsule.mapper.UserMapper;
import sd.zhr.moodcapsule.mapper.UserRoleMapper;
import sd.zhr.moodcapsule.pojo.User;
import sd.zhr.moodcapsule.pojo.UserRole;

@CrossOrigin
@RestController
public class LoginController {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    //没有认证，需要前段登录的提示
    @GetMapping("/login_page")
    public Wrapper<String> daylist(){
        return WrapMapper.wrap(Wrapper.NOT_LOGIN_CODE,
                Wrapper.NOT_LOGIN_MESSAGE,"请登录");
    }
    //注册
    @PostMapping("/register")
    public Wrapper<String> register(@RequestBody User user){
        //还需要检查用户名是否重复 重复返回用户名重复注册失败
        // 1. 设置默认值
        user.setPassword(passwordEncoder.encode(user.getPassword())); // 加密密码
        user.setValid(1); // 默认用户状态为有效
        user.setAvatar_url("https://example.com/avatar1.jpg"); // 默认头像链接

        // 2. 插入用户数据
        userMapper.insert(user);
        // 3. 分配默认角色（普通用户）
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId()); // 用户 ID
        userRole.setRoleId(2); // 假设 2 是普通用户的角色 ID
        userRoleMapper.insert(userRole);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,
                Wrapper.SUCCESS_MESSAGE,"注册成功");
    }
}
